from distutils.log import error
from flask import request
from sqlalchemy import true
from SQLConfig import app
import constants
import os
from updateProjectFile import changeProjectFile


@app.route('/uploadImage', methods=['Get', 'POST'])
def uploadImage():  # put application's code here
    """
    用于上传文件

    patientId：患者id
    distance：距离信息
    pictureGroup：上传图片的组数，类型为int
    """

    patientId = request.form.get("patientId")
    file = request.files.get("file")
    showname = request.form.get("showname")
    color = request.form.get("color")
    # visible = request.form.get("visible")
    if patientId is None or patientId == "":
        raise error("patientId is None")

    url = save_file(file, patientId, constants.patientStlUrl)

    changeProjectFile(patientId, "stlFiles", "insert", 0, {
        "filename": os.path.basename(url),
        "showname": showname,
        "color": color,
        "visible": "true",
        "transform_matrix": {
            "element":[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]
        }
    })
    return "OK"


def save_file(file, patientId, patientStlUrl):
    """
    保存文件

    :param patientStlUrl:
    :param file: 文件
    :param patientId: 病人id（子文件夹）
    :return: 保存的状态
    """
    # 如果没有发送文件
    if file is None:
        return "no file"
    if not os.path.exists(os.path.join(constants.patientBaseUrl, patientId, patientStlUrl)):
        os.makedirs(os.path.join(constants.patientBaseUrl, patientId, patientStlUrl))
    url = os.path.join(constants.patientBaseUrl, patientId, patientStlUrl, file.filename)
    url=check(url)
    file.save(url)  # 保存文件
    return url


def check(filename):
    n = [0]

    def check_meta(file_name):
        file_name_new = file_name
        if os.path.isfile(file_name):
            file_name_new = file_name[:file_name.rfind('.')] + '_' + str(n[0]) + file_name[file_name.rfind('.'):]
            n[0] += 1
        if os.path.isfile(file_name_new):
            file_name_new = check_meta(file_name)
        return file_name_new

    return check_meta(filename)
